/**
 * @file 工单列表
 * @author yangjiangming <449654337@qq.com>
 * @date 2018/11/27 10:20:40
 */

layui.define(['element', 'layer', 'form', 'table', 'zmnTable', 'formSelects', 'zmnSearch', 'lodash', 'select2', 'searchPage', 'zmnSelect', 'zmnOmsSelect'], function(exports) {
    var $ = layui.$;
    var form = layui.form;
    var layer = layui.layer;
    var table = layui.table;
    var zmnTable = layui.zmnTable;
    var zmnUtils = layui.zmnUtils;
    var zmnSearch = layui.zmnSearch;
    var searchPage = layui.searchPage;
    var lodash = layui.lodash;
    var select2;
    var formSelects = layui.formSelects;
    var element = layui.element;
    var $http = layui.$http;
    let zmnOmsSelect = layui.zmnOmsSelect;
    let zmnSelect = layui.zmnSelect;

    let json = {
        vo: {
            limitPermit: false
        }
    };


    var tableInstance = null;
    // 当前操作的工单
    window.currentWork = {};

    // 服务公司查询 URL
    var MANAGE_COMPANY_URL = '/company/manage/company/list.action';

    // 操作员远程查询 URL
    var OPERATOR_LIST_URL = '/staff/staff/company/list.action';

    // 部分下的 操作员远程查询 URL
    var OPERATOR_LIST_WITH_DEPT_ID_URL = '/staff/dept/staff/list.action';

    var datePickerSelectorArray = [
        'receiveTime', // 接单时间
        'replyVisitTime' // 回访时间
    ];

    var multipleSelectNameArray = [
        'workStatus',
        'showCategTwoIdList',
        'manageCompanyIdList',
    ];

    /**
     * 延迟加载
     * @param func 处理函数
     * @param timeout 延迟时间
     */
    function lazyLoad(func, timeout) {
        setTimeout(func, timeout || 0);
    }

    /**
     * 初始页时间选择器
     * @private
     */
    function _initALLDatePickers() {
        zmnSearch.renderDatePicker(datePickerSelectorArray);
    }

    /**
     * 格式化器
     * @type {{}}
     */
    var formattor = {
        dateFormaterForReceiveTime: (data) => {
            if (data['receiveTime'])
                return layui.util.toDateString(data['receiveTime']);
            else
                return "";
        },
        dateFormaterForReplyVisitTime: (data) => {
            if (data['replyVisitTime'])
                return layui.util.toDateString(data['replyVisitTime']);
            else
                return "";
        }
    };


    /**
     * 搜索框搜索方法
     * @param {object} params 查询参数
     */
    function searchForTable(params, data) {
        tableInstance = renderTable(params, data);
    }


    /**
     * 根据工单 id 更新行数据
     * @param workId
     */
    function updateRowDataByWorkId() {};

    window.updateRowDataByWorkId = updateRowDataByWorkId;

    /**
     * 标准化搜索参数
     * @param {object} field 参数
     */
    function normalizeSearchParams(field) {
        var params = {};

        // 整理时间
        datePickerSelectorArray.forEach(function(keyword) {
            var startSelector = keyword + '.start';
            var endSelector = keyword + '.end';

            if ($('#' + keyword + 'Start').closest('.date-picker-item').hasClass('inline-block')) {
                var startTime = field[startSelector];
                var endTime = field[endSelector];

                if (startTime || endTime) {
                    startTime = startTime ? startTime + ' ' + '00:00:00' : '';
                    endTime = endTime ? endTime + ' ' + '23:59:59' : '';

                    params[keyword] = startTime + ',' + endTime;
                }
            }

            field[startSelector] = '';
            field[endSelector] = '';
        });

        // 整理操作类型、操作员
        if (field['operate_operatorId']) {
            params['replyVisitId'] = field['operate_operatorId'];
            field['operate_operatorId'] = null;
        }

        // 拷贝非空字段
        Object.keys(field).filter((key) => {
            if (field[key]) {
                if (multipleSelectNameArray.indexOf(key) !== -1) {
                    params[key] = field[key].split(',');
                } else {
                    params[key] = field[key];
                }
            }
        });
        params['platWork'] = plat;
        return params;
    }

    // 表格配置
    var tableConfig = {
        defaultParams: {},
        initialSearch: false,
        orderObj: {},
        exportURL: '/question/replyvisit/export',
        config: {
            url: '/question/replyvisit/ajax/list.action',
            cols: [
                [
                    { templet: '#index', title: '序号' },
                    { field: 'receiveTime', title: '下单时间', templet: formattor.dateFormaterForReceiveTime },
                    { field: 'orderId', title: '工单号' },
                    { field: 'replyVisiterName', title: '回访人' },
                    { field: 'replyItemName', title: '回访项目' },
                    { field: 'replyVisitTime', title: '回访时间', templet: formattor.dateFormaterForReplyVisitTime },
                    { field: 'companyName', title: '子公司' },
                    { field: 'manageCompanyName', title: '服务公司' },
                    { field: 'showCategTwoName', title: '维修品类' },
                    { field: 'masterName', title: '工程师' },
                    { field: 'statusName', title: '工单状态' }
                ]
            ]
        }
    };

    /**
     * 渲染表格
     * @param {object} params 查询参数
     * @returns {object}
     */
    function renderTable(params, data) {
        return zmnTable.init({
            config: {
                ...tableConfig.config,
                elem: '#zmn-replyQuestion-table',
                id: 'zmn-replyQuestion-table',
                method: 'POST',
                contentType: 'application/json;charset=utf-8',
                limit: 100,
                limits: [100],
                data: data,
                where: {
                    ...tableConfig.orderObj,
                    ...params
                },
                parseData: function(res) {
                    return {
                        "code": res.status, //解析接口状态
                        "msg": res.message, //解析提示文本
                        "count": res.data ? (res.data.count > 10000 ? 10000 : res.data.count) : 0, //解析数据长度
                        "data": res.data ? res.data.data : [] //解析数据列表
                    };
                },
                done: function(res, curr, count) {
                    $('.layui-this').find('.count').text('（共 ' + count + ' 条）');
                }
            },
            filter: 'zmn-replyQuestion-table',

            event: function() {
                table.on('tool(zmn-work-table)', function(rowObj) {
                    if (rowObj.event === 'operate') {}
                });

                table.on('rowDouble(zmn-work-table)', function(rowObj) {

                });

                // 监听头工具栏事件
                table.on('toolbar(zmn-work-table)', function(obj) {

                });
            }
        });
    }

    /**
     * 初始化页面事件
     */
    function initEvent() {
        $('body').on('blur', 'input', function() {
            var $this = $(this);
            $this.val($this.val().replace(/(^\s*)|(\s*$)/g, ''));
        });

        // 监听重置按钮点击
        $('#btn-clean').on('click', function() {
            setTimeout(function() {
                $('input:not([type="checkbox"][lay-filter="datepicker"])').val('');
                $('select').val('');

                var $multiSelectList = $('select[xm-select]');
                $multiSelectList.each(function() {
                    var xmSelect = $(this).attr('xm-select');
                    formSelects.value(xmSelect, []);
                });

            }, 100);
        });

        // 监听时间选择器控制选择框点击事件
        form.on('checkbox(datepicker)', function(data) {
            var $dataPicker = $('.date-picker-item').eq(data.value);
            if (data.elem.checked) {
                $dataPicker.addClass('inline-block').find('input').attr('disabled', false);
            } else {
                $dataPicker.removeClass('inline-block').find('input').attr('disabled', false);
            }

            form.render();
        });

        // 监听查询表单提交事件
        form.on('submit(submit-search)', function(obj) {
            var params = normalizeSearchParams(obj.field);
            if (!Object.keys(params).length) {
                layer.msg('请至少选择一个查询条件');
                return false;
            }

            // tableInstance.search(params);
            searchForTable(params);
            return false;
        });

        // 监听查询表单导出事件
        form.on('submit(submit-export)', function(obj) {
            let params = normalizeSearchParams(obj.field);
            console.log(params);
            if (!Object.keys(params).length) {
                layer.msg('请至少选择一个查询条件');
                return false;
            }

            if (!tableConfig.exportURL) {
                layer.msg('请添加导出 URL');
                return false;
            }
            layer.tips('至多导出 5000 条', obj.elem, {
                success: function() {
                    setTimeout(function() {
                        layui.zmnUtils.exportFile(tableConfig.exportURL, params);
                    }, 300);
                }
            });

            return false;
        });

        element.on('tab(workListTabBrief)', function(obj) {
            var type = $(this).data('type');

            if (type === -1) {
                return;
            }

            renderTable({ tabType: type });
        });
    }

    function initAllSelect() {
        zmnSelect.selectProdCategTwo('showCategTwoIdList');
        // 工单状态
        zmnOmsSelect.selectWorkStatus('workStatusList');
        zmnSelect.selectlSubCompaniesCity({
            subCompanySelectId: 'companyId',
            spCompanySelectId: 'manageCompanyIdList',
        }, {
            subCompanySelectId: {
                isRadio: true,
                remote: {
                    limitPermit: json.vo.limitPermit,
                    events: {
                        extendParams: function() {
                            return { plat: plat }
                        }
                    }
                }
            },
            spCompanySelectId: {
                isRadio: true
            }
        });

        zmnSelect.searchStaff('operate_operatorId', {
            remote: {
                limitPermit: json.vo.limitPermit,
                events: {
                    extendParams: function() {
                        return {
                            deptIdList: dpermitDeptIdList && dpermitDeptIdList.length > 0 ? dpermitDeptIdList : null,
                            orgIdList: dpermitOrgIdList && dpermitOrgIdList.length > 0 ? dpermitOrgIdList : null,
                            status: 2
                        }
                    }
                }
            }
        });

        // 用户层级
        zmnOmsSelect.selectUserLevelList('userLevel');
    }
    /**
     * 初始化页面
     */
    function initPage() {

        initAllSelect();

        // 初始化页面所有的日期选择器
        _initALLDatePickers();

        lazyLoad(function() {
            // 初始化页面所有的日期选择器
            layui.use('select2', function(select2Module) {
                select2 = select2Module;
            });
        });

        $('body').append('<div class="page-loaded"></div>');
    }

    searchPage.init({
        id: 'zmn-work-table',
        searchURL: '/question/replyvisit/ajax/list.action',
        exportURL: '/question/replyvisit/export',
        defaultParams: {},
        orderObj: {
            orderField: 'receiveTime',
            defaultOrder: 2,
            platWork: plat
        },
        tableConfig: {
            toolbar: '#toolbarDemo',
            defaultToolbar: ['filter', 'print']
        },
        init: function() {
            initEvent();
            initPage();
        },
        parseParams: function(dataObj) {
            let pageUrl = window.location.href;
            var params = normalizeSearchParams(dataObj.field)
            var filter_name = ''
            Object.keys(params).forEach((item, index) => {
                var fifname = $('[name^="' + item + '"]').parents('.layui-input-inline').eq($('[name^="' + item + '"]').parents('.layui-input-inline').length - 1).prev().text().split('：')[0]

                if (index != Object.keys(params).length - 1) {
                    filter_name = filter_name + fifname + '|'
                } else {
                    filter_name = filter_name + fifname
                }

            })
            try {
                if (filter_name.substring(filter_name.length - 1) == '|') {
                    filter_name = filter_name.substring(0, filter_name.length - 1)
                }
                console.log(filter_name)
                var data = {
                    employee_name: loginStaff.realName, // 内部员工姓名,
                    employee_id: loginStaff.staffId,
                    department_name: loginStaff.deptName, // 员工部门名称
                    department_id: loginStaff.deptId,
                    menu: path_name, //菜单目录路径名称
                    filter_name: filter_name,
                    tab_name: tabName || ''
                }
                webTrackingUtil('SYS_ADMIN_QUERY', pageUrl, 'click', 'SYS_ADMIN_QUERY_CLICK', data)
            } catch (error) {
                console.log(error)
            }

            return params;//normalizeSearchParams(dataObj.field);
        },
        rowDoubleHandler: function(rowObj) {},
        toolbarHandler: function(obj) {},
        toolHandler: function(obj) {}
    });

    exports('question_replyvisit_list');
});